package com.jason.auto.controller;

import com.jason.auto.model.User;
import com.jason.auto.proto.cs.user.UserEditRequest;
import com.jason.auto.proto.cs.user.UserQueryRequest;
import com.jason.auto.common.GeneralResult;
import com.jason.auto.common.PageResult;
import com.jason.auto.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("list")
    public PageResult getUserList(@RequestBody UserQueryRequest userQueryRequest) {
        PageResult result = new PageResult();
        Page<User> userByPage = userService.findUserByPage(userQueryRequest);
        result.setData(userByPage.getContent());
        result.setCount(userByPage.getTotalElements());
        return result;
    }

    @PostMapping("del/{userId}")
    public GeneralResult deleteUser(@PathVariable Long userId) {
        GeneralResult result = new GeneralResult();
        userService.delete(userId);
        return result;
    }

    /**
     * 批量删除
     */
    @PostMapping("batch_del")
    public GeneralResult batchDelete(String userIds) {
        GeneralResult result = new GeneralResult();
        List<Long> idList = Arrays.asList(userIds.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        userService.batchDelete(idList);
        return result;
    }

    @PostMapping("edit")
    public GeneralResult editUser(@RequestBody UserEditRequest userEdit) {
        GeneralResult result = new GeneralResult();
        userService.edit(userEdit);
        return result;
    }
}